from pathlib import Path
from typing import Dict, Any, Optional
import io
import logging
from datetime import datetime

# 导出相关库
try:
    from reportlab.lib.pagesizes import letter, A4
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.units import inch
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.lib import colors
    REPORTLAB_AVAILABLE = True
except ImportError:
    REPORTLAB_AVAILABLE = False
    logging.warning("ReportLab not available, PDF export disabled")

try:
    from docx import Document
    from docx.shared import Inches
    from docx.enum.text import WD_ALIGN_PARAGRAPH
    from docx.oxml.shared import OxmlElement, qn
    DOCX_AVAILABLE = True
except ImportError:
    DOCX_AVAILABLE = False
    logging.warning("python-docx not available, Word export disabled")

logger = logging.getLogger(__name__)


class ExportService:
    """导出服务"""

    def __init__(self):
        self.supported_formats = ["markdown"]
        if REPORTLAB_AVAILABLE:
            self.supported_formats.append("pdf")
        if DOCX_AVAILABLE:
            self.supported_formats.append("docx")

    def get_supported_formats(self) -> list:
        """获取支持的导出格式"""
        return self.supported_formats.copy()

    async def export_to_markdown(
        self,
        minutes_data: Dict[str, Any],
        template_name: Optional[str] = None
    ) -> str:
        """导出为Markdown格式"""
        try:
            # 构建Markdown内容
            content = []

            # 标题
            title = minutes_data.get("title", "会议纪要")
            content.append(f"# {title}\n")

            # 会议信息
            meeting_info = []
            if minutes_data.get("meeting_time"):
                meeting_info.append(f"**会议时间：** {minutes_data['meeting_time']}")
            if minutes_data.get("attendees"):
                attendees = ", ".join(minutes_data["attendees"])
                meeting_info.append(f"**参会人员：** {attendees}")

            if meeting_info:
                content.append("## 会议信息\n")
                for info in meeting_info:
                    content.append(f"{info}\n")
                content.append("")

            # 概要
            if minutes_data.get("summary"):
                content.append("## 会议概要\n")
                content.append(f"{minutes_data['summary']}\n")

            # 主要议题
            if minutes_data.get("key_points"):
                content.append("## 主要议题\n")
                for i, point in enumerate(minutes_data["key_points"], 1):
                    content.append(f"{i}. {point}\n")
                content.append("")

            # 决定事项
            if minutes_data.get("decisions"):
                content.append("## 决定事项\n")
                for i, decision in enumerate(minutes_data["decisions"], 1):
                    content.append(f"{i}. {decision}\n")
                content.append("")

            # 行动计划
            if minutes_data.get("action_items"):
                content.append("## 行动计划\n")
                for i, action in enumerate(minutes_data["action_items"], 1):
                    content.append(f"{i}. **{action.get('description', '')}**")
                    if action.get("assignee"):
                        content.append(f"   - 负责人：{action['assignee']}")
                    if action.get("due_date"):
                        content.append(f"   - 截止日期：{action['due_date']}")
                    if action.get("priority"):
                        priority_map = {"high": "高", "medium": "中", "low": "低"}
                        content.append(f"   - 优先级：{priority_map.get(action['priority'], action['priority'])}")
                    content.append("")

            # 生成时间
            content.append(f"\n---\n*生成时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*")

            return "\n".join(content)

        except Exception as e:
            logger.error(f"Error exporting to Markdown: {e}")
            raise

    async def export_to_pdf(
        self,
        minutes_data: Dict[str, Any],
        template_name: Optional[str] = None
    ) -> bytes:
        """导出为PDF格式"""
        if not REPORTLAB_AVAILABLE:
            raise ValueError("PDF export not available - ReportLab not installed")

        try:
            # 创建字节流
            buffer = io.BytesIO()
            doc = SimpleDocTemplate(buffer, pagesize=A4)

            # 获取样式
            styles = getSampleStyleSheet()

            # 自定义样式
            title_style = ParagraphStyle(
                'CustomTitle',
                parent=styles['Heading1'],
                fontSize=18,
                spaceAfter=30,
                alignment=1  # 居中
            )

            heading_style = ParagraphStyle(
                'CustomHeading',
                parent=styles['Heading2'],
                fontSize=14,
                spaceAfter=12
            )

            # 构建内容
            story = []

            # 标题
            title = minutes_data.get("title", "会议纪要")
            story.append(Paragraph(title, title_style))
            story.append(Spacer(1, 20))

            # 会议信息
            meeting_info = []
            if minutes_data.get("meeting_time"):
                meeting_info.append(f"会议时间：{minutes_data['meeting_time']}")
            if minutes_data.get("attendees"):
                attendees = ", ".join(minutes_data["attendees"])
                meeting_info.append(f"参会人员：{attendees}")

            if meeting_info:
                story.append(Paragraph("会议信息", heading_style))
                for info in meeting_info:
                    story.append(Paragraph(info, styles['Normal']))
                story.append(Spacer(1, 12))

            # 概要
            if minutes_data.get("summary"):
                story.append(Paragraph("会议概要", heading_style))
                story.append(Paragraph(minutes_data["summary"], styles['Normal']))
                story.append(Spacer(1, 12))

            # 主要议题
            if minutes_data.get("key_points"):
                story.append(Paragraph("主要议题", heading_style))
                for i, point in enumerate(minutes_data["key_points"], 1):
                    story.append(Paragraph(f"{i}. {point}", styles['Normal']))
                story.append(Spacer(1, 12))

            # 决定事项
            if minutes_data.get("decisions"):
                story.append(Paragraph("决定事项", heading_style))
                for i, decision in enumerate(minutes_data["decisions"], 1):
                    story.append(Paragraph(f"{i}. {decision}", styles['Normal']))
                story.append(Spacer(1, 12))

            # 行动计划
            if minutes_data.get("action_items"):
                story.append(Paragraph("行动计划", heading_style))
                for i, action in enumerate(minutes_data["action_items"], 1):
                    action_text = f"{i}. {action.get('description', '')}"
                    if action.get("assignee"):
                        action_text += f" - 负责人：{action['assignee']}"
                    if action.get("due_date"):
                        action_text += f" - 截止日期：{action['due_date']}"
                    story.append(Paragraph(action_text, styles['Normal']))
                story.append(Spacer(1, 12))

            # 生成时间
            story.append(Paragraph(f"生成时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", styles['Normal']))

            # 生成PDF
            doc.build(story)

            # 获取字节数据
            buffer.seek(0)
            return buffer.getvalue()

        except Exception as e:
            logger.error(f"Error exporting to PDF: {e}")
            raise

    async def export_to_docx(
        self,
        minutes_data: Dict[str, Any],
        template_name: Optional[str] = None
    ) -> bytes:
        """导出为Word格式"""
        if not DOCX_AVAILABLE:
            raise ValueError("Word export not available - python-docx not installed")

        try:
            # 创建文档
            doc = Document()

            # 标题
            title = minutes_data.get("title", "会议纪要")
            title_paragraph = doc.add_heading(title, 0)
            title_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

            # 会议信息
            meeting_info = []
            if minutes_data.get("meeting_time"):
                meeting_info.append(f"会议时间：{minutes_data['meeting_time']}")
            if minutes_data.get("attendees"):
                attendees = ", ".join(minutes_data["attendees"])
                meeting_info.append(f"参会人员：{attendees}")

            if meeting_info:
                doc.add_heading("会议信息", level=1)
                for info in meeting_info:
                    doc.add_paragraph(info)

            # 概要
            if minutes_data.get("summary"):
                doc.add_heading("会议概要", level=1)
                doc.add_paragraph(minutes_data["summary"])

            # 主要议题
            if minutes_data.get("key_points"):
                doc.add_heading("主要议题", level=1)
                for i, point in enumerate(minutes_data["key_points"], 1):
                    doc.add_paragraph(f"{i}. {point}")

            # 决定事项
            if minutes_data.get("decisions"):
                doc.add_heading("决定事项", level=1)
                for i, decision in enumerate(minutes_data["decisions"], 1):
                    doc.add_paragraph(f"{i}. {decision}")

            # 行动计划
            if minutes_data.get("action_items"):
                doc.add_heading("行动计划", level=1)
                for i, action in enumerate(minutes_data["action_items"], 1):
                    action_text = f"{i}. {action.get('description', '')}"
                    if action.get("assignee"):
                        action_text += f" - 负责人：{action['assignee']}"
                    if action.get("due_date"):
                        action_text += f" - 截止日期：{action['due_date']}"
                    doc.add_paragraph(action_text)

            # 生成时间
            doc.add_paragraph(f"生成时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

            # 保存到字节流
            buffer = io.BytesIO()
            doc.save(buffer)
            buffer.seek(0)
            return buffer.getvalue()

        except Exception as e:
            logger.error(f"Error exporting to Word: {e}")
            raise

    async def export_minutes(
        self,
        minutes_data: Dict[str, Any],
        format_type: str,
        template_name: Optional[str] = None
    ) -> bytes:
        """导出会议纪要"""
        if format_type not in self.supported_formats:
            raise ValueError(f"Unsupported format: {format_type}")

        try:
            if format_type == "markdown":
                content = await self.export_to_markdown(minutes_data, template_name)
                return content.encode('utf-8')
            elif format_type == "pdf":
                return await self.export_to_pdf(minutes_data, template_name)
            elif format_type == "docx":
                return await self.export_to_docx(minutes_data, template_name)
            else:
                raise ValueError(f"Unsupported format: {format_type}")

        except Exception as e:
            logger.error(f"Error exporting minutes: {e}")
            raise

    def get_content_type(self, format_type: str) -> str:
        """获取内容类型"""
        content_types = {
            "markdown": "text/markdown",
            "pdf": "application/pdf",
            "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        }
        return content_types.get(format_type, "application/octet-stream")

    def get_file_extension(self, format_type: str) -> str:
        """获取文件扩展名"""
        extensions = {
            "markdown": ".md",
            "pdf": ".pdf",
            "docx": ".docx"
        }
        return extensions.get(format_type, ".txt")